<?php
declare(strict_types=1);

namespace Service\MemberService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\MemberCollection;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsBrand;
use Service\GoodsBrandService\BrandService;
/**
 * TO C/B SBBC用户收藏
 * @author hj
 */
class MemberCollectionService extends BaseService
{
    /**
     * 收藏列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function collectionList(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $fields = ['type', 'belong_id', 'cd'];
        $result = MemberCollection::where('mid', $param['mid'])->where('df', 0)->orderBy('id', 'desc')->select($fields)->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $collection = $result->getCollection();
        $goods_ids  = $collection->where('type', 1)->pluck('belong_id')->toArray();
        $brand_ids  = $collection->where('type', 2)->pluck('belong_id')->toArray();
        $allGoods   = [];//商品列表等统一写好了再来搞------------------------------------------------
        $allBrand   = BrandService::getBrand($brand_ids);
        $collection->each(function ($item, $key) use ($allGoods, $allBrand) {
            $item->item = [];
            if ($item->type == 1) {
                $item->item = $allGoods[$item->id] ?? [];//商品
            }
            if ($item->type == 2) {
                $item->item = $allBrand[$item->id] ?? [];
            }
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $collection->toArray());
    }

    /**
     * 添加收藏
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function add(array $param)
    {
        $validateRes = self::addArgumentValidate($param);
        if ($validateRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $validateRes['msg'] ?? 'invalid argument');
        }
        $addData = [
            'sid'       => getSID(),
            'mid'       => $param['mid'],
            'type'      => $param['type'],
            'belong_id' => $param['id'],
            'cd'        => time(),
        ];
        $result  = MemberCollection::insert($addData);
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '收藏失败');
        }
        return Normal::returnCode(Normal::SUC, '收藏成功');
    }

    /**
     * 取消收藏
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function cancel(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['belong_id']) || empty($param['belong_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['belong_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument belong_id');
        }
        if (!isset($param['type']) || !in_array($param['type'], ['1', '2'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument type');
        }
        $result = MemberCollection::where('type', $param['type'])->where('belong_id', $param['belong_id'])->where('mid', $param['mid'])->update(['df' => 1, 'md' => time()]);
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '取消失败');
        }
        return Normal::returnCode(Normal::SUC, '取消成功');
    }

    /**
     * 添加参数验证
     * @author: hj
     */
    private static function addArgumentValidate($param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        $member = Member::where('mid', (int)($param['mid']))->exists();
        if (empty($member)) {
            return Normal::returnCode(Normal::FAIL, '用户不存在');
        }
        if (!isset($param['id']) || empty($param['id']) || (preg_match("/^[1-9]\d*$/", (string)$param['id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument id');
        }
        if (!isset($param['type']) || !in_array($param['type'], ['1', '2'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument type');
        }
        if (isset($param['type']) && $param['type'] == 1) {
            $goods = Goods::where('id', $param['id'])->where('status', 1)->where('df', 0)->exists();
            if (empty($goods)) {
                return Normal::returnCode(Normal::FAIL, "收藏的商品不存在");
            }
        }
        if (isset($param['type']) && $param['type'] == 2) {
            $brand = GoodsBrand::where('id', $param['id'])->where('df', 0)->exists();
            if (empty($brand)) {
                return Normal::returnCode(Normal::FAIL, "收藏的品牌不存在");
            }
        }
        $col = MemberCollection::where('belong_id', $param['id'])->where('mid', $param['mid'])->where('type', $param['type'])->where('df', 0)->exists();
        if ($col) {
            return Normal::returnCode(Normal::FAIL, "收藏的" . MemberCollection::$type[$param['type']] . "不存在");
        }
        return Normal::returnCode(Normal::SUC, '验证通过');
    }
}